import React, { useEffect } from 'react';
import { Form, Input, Dialog, Textarea } from 'tdesign-react';
import { FormProps } from 'tdesign-react';
import { JupiterRole } from '../../../types/roleTypes';

const { FormItem } = Form;

interface Props {
    visible: boolean;
    onClose: () => void;
    onSubmit: (data: Partial<JupiterRole>) => void;
    initialData?: Partial<JupiterRole>;
    title: string;
}

export default function RoleForm({
    visible,
    onClose,
    onSubmit,
    initialData = {},
    title,
}: Props) {
    const [form] = Form.useForm();

    // 监听 visible，每次打开都重置并填充最新数据
    useEffect(() => {
        if (visible) {
            // 先清空上一次的值
            form.reset();
            // 再设置新的初始值
            form.setFieldsValue({
                name: initialData?.name || '',
                description: initialData?.description || '',
            });
        }
    }, [visible, initialData, form]);

    const handleSubmit: FormProps['onSubmit'] = ({ validateResult, fields }) => {
        if (validateResult === true) {
            onSubmit(fields as Partial<JupiterRole>);
        }
    };

    const handleClose = () => {
        form.reset(); // 关闭时清空
        onClose();
    };

    return (
        <Dialog
            closeOnOverlayClick={false}
            header={title}
            visible={visible}
            onClose={handleClose}
            onConfirm={() => form.submit()}
            width={500}
        >
            <Form
                form={form}
                layout="vertical"
                onSubmit={handleSubmit}
            >
                <FormItem
                    label="角色名称"
                    name="name"
                    rules={[{ required: true, message: '请输入角色名称' }]}
                >
                    <Input placeholder="请输入角色名称" />
                </FormItem>

                <FormItem
                    label="描述"
                    name="description"
                >
                    <Textarea
                        placeholder="请输入角色描述"
                        rows={3}
                    />
                </FormItem>
            </Form>
        </Dialog>
    );
}
